package view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;

public class ChangePasswordPage extends JDialog {
	JLabel labelMessage;
	String editorUsername;
	String editorLevel;
	private JTextField textFieldEditorUsername;
	private JTextField textFieldEditorLevel;
	private JPasswordField passwordFieldCurrent;
	private JPasswordField passwordFieldNew;
	private JPasswordField passwordFieldConfirm;

	/**
	 * Launch the application.
	 */
	public void execute() {
		try {
			setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			setModal(true);
			setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public ChangePasswordPage(String edUsername, String edLevel) {
		editorUsername = edUsername;
		editorLevel = edLevel;
		setResizable(false);
		setBounds(100, 100, 450, 277);
		getContentPane().setLayout(new MigLayout("", "[grow][grow][grow][]", "[][][][][][][][][][]"));
		{
			JLabel lblJaLibrary = new JLabel("J&A Library");
			lblJaLibrary.setFont(new Font("Arial", Font.BOLD, 16));
			lblJaLibrary.setForeground(Color.BLUE);
			getContentPane().add(lblJaLibrary, "cell 0 0 4 1,alignx center");
		}
		{
			JLabel lblChangePassword = new JLabel("Change Password");
			getContentPane().add(lblChangePassword, "cell 0 1 4 1,alignx center");
		}
		{
			JLabel label = new JLabel("     ");
			getContentPane().add(label, "cell 0 2");
		}
		{
			JLabel lblEnterCurrentPassword = new JLabel("Enter Current Password:");
			getContentPane().add(lblEnterCurrentPassword, "cell 0 3,alignx trailing");
		}
		{
			passwordFieldCurrent = new JPasswordField();
			getContentPane().add(passwordFieldCurrent, "cell 1 3 2 1,growx");
		}
		{
			JLabel lblNewPassword = new JLabel("New Password:");
			getContentPane().add(lblNewPassword, "cell 0 4,alignx trailing");
		}
		{
			passwordFieldNew = new JPasswordField();
			getContentPane().add(passwordFieldNew, "cell 1 4 2 1,growx");
		}
		{
			JLabel lblConfirmNewPassword = new JLabel("Confirm New Password:");
			getContentPane().add(lblConfirmNewPassword, "cell 0 5,alignx trailing");
		}
		{
			passwordFieldConfirm = new JPasswordField();
			getContentPane().add(passwordFieldConfirm, "cell 1 5 2 1,growx");
		}
		{
			JLabel label = new JLabel("     ");
			getContentPane().add(label, "cell 0 6");
		}
		{
			JButton btnChangePassword = new JButton("Change Password");
			btnChangePassword.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					//TODO
					if (isValidPasswordChange()) {
						updatePassword();
					}
				}
			});
			getContentPane().add(btnChangePassword, "cell 0 7,growx");
		}
		{
			JButton btnBack = new JButton("Back");
			btnBack.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					dispose();
				}
			});
			getContentPane().add(btnBack, "cell 3 7");
		}
		{
			labelMessage = new JLabel("     ");
			labelMessage.setForeground(Color.BLUE);
			getContentPane().add(labelMessage, "cell 0 8 4 1");
		}
		{
			textFieldEditorUsername = new JTextField();
			textFieldEditorUsername.setEditable(false);
			textFieldEditorUsername.setText(editorUsername);
			getContentPane().add(textFieldEditorUsername, "cell 0 9 2 1,growx");
			textFieldEditorUsername.setColumns(10);
		}
		{
			textFieldEditorLevel = new JTextField();
			textFieldEditorLevel.setEditable(false);
			textFieldEditorLevel.setText(editorLevel);
			getContentPane().add(textFieldEditorLevel, "cell 2 9 2 1,growx");
			textFieldEditorLevel.setColumns(10);
		}
	}
	
	private boolean isValidPasswordChange() {
		String curPass = String.copyValueOf(passwordFieldCurrent.getPassword());
		String newPass = String.copyValueOf(passwordFieldNew.getPassword());
		String conPass = String.copyValueOf(passwordFieldConfirm.getPassword());
		boolean curPassOK =false;
		
		Connection con = null;
		try {
			System.out.println("connecting...");
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/librarydb", "root", ""); // null
																			// password
			if (!con.isClosed())
				System.out.println("Sucessfully connected.");
			else
				System.out.println("");

			Statement statement = con.createStatement();
			ResultSet result = statement
					.executeQuery("select userid from user where userid='"
							+ editorUsername + "' AND password='"+curPass+"'");
			System.out.println("here");
			if (result.next()) {
				curPassOK = true;
			}

		} catch (Exception e) {
			System.err.println("Exception: " + e.getMessage());

		} finally {
			try {
				con.close();
			} catch (SQLException e) {
			}
		}
		
		if (!curPassOK) {
			labelMessage.setText("Invalid current password.");
			return false;
		}
		
		if (conPass.trim().equals(newPass.trim())) {
			//TODO: update password.
			labelMessage.setText("Password updated.");
		}
		else {
			labelMessage.setText("The New and Confirm passwords should be the same.");
			return false;
		}
		return true;
	}
	
	private void updatePassword() {
		String newPass = String.copyValueOf(passwordFieldNew.getPassword());
		String conPass = String.copyValueOf(passwordFieldConfirm.getPassword());
		Connection con = null;
		try {
			System.out.println("connecting...");
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/librarydb", "root", ""); // null
																			// password
			if (!con.isClosed())
				System.out.println("Sucessfully connected.");
			else
				System.out.println("");

			Statement statement = con.createStatement();
			statement.executeUpdate("update user set password='" + newPass+"'");

		} catch (Exception e) {
			System.err.println("Exception: " + e.getMessage());

		} finally {
			try {
				con.close();
			} catch (SQLException e) {
			}
		}
	}

}
